#ifndef BLOCKDICTIONARY_H
#define BLOCKDICTIONARY_H
#include<cstddef>
#include<vector>
#include<string>
#include<iostream>
using std::string;
using std::vector;
using std::ostream;
using std::endl;
class BlockDictionary
{
    public:
    int termsize;
    int* termid;
    int* docfq;
    size_t* startbyte;
    size_t* bytenum;
    int len;
    BlockDictionary(int num = LEXICON_SIZE)
    {
        termsize = num;
        len = 0;
        termid = new int[termsize];
        docfq = new int[termsize];
        startbyte = new size_t[termsize];
        bytenum = new size_t[termsize];
    }
    ~BlockDictionary()
    {
    }
    void clear()
    {
        len = 0;
    }
    void free()
    {
        delete[] termid;
        delete[] docfq;
        delete[] startbyte;
        delete[] bytenum;
    }
    void push(int tid,int df,size_t sb,size_t bn)
    {
        termid[len]= tid;
        docfq[len] = df;
        startbyte[len] = sb;
        bytenum[len] = bn;
        ++len;
    }
    void fromfile(string filename)
    {
        len = 0;
        struct stat statbuf;
        stat(filename.c_str(),&statbuf);
        int fid = open(filename.c_str(),O_RDONLY);
        char *back_buf = reinterpret_cast<char*>(mmap(NULL,statbuf.st_size,PROT_READ,MAP_PRIVATE,fid,0));
        len = *(reinterpret_cast<int*>(back_buf));


        int *intptr = reinterpret_cast<int*>(back_buf+sizeof(int));
        for(int i=0; i<len; ++i,++intptr)
            termid[i] = *intptr;
        for(int i=0; i<len; ++i,++intptr)
            docfq[i] = *intptr;
        size_t *stptr = reinterpret_cast<size_t*>(intptr);
        for(int i=0; i<len; ++i,++stptr)
            startbyte[i] = *stptr;
        for(int i=0; i<len; ++i,++stptr)
            bytenum[i] = *stptr;
        munmap(back_buf,statbuf.st_size);
        close(fid);
    }
    void tofile(string filename)
    {
        FILE* fid = fopen(filename.c_str(),"w");
        fwrite(reinterpret_cast<char*>(&len),sizeof(int),1,fid);
        fwrite(reinterpret_cast<char*>(termid),sizeof(int),len,fid);
        fwrite(reinterpret_cast<char*>(docfq),sizeof(int),len,fid);
        fwrite(reinterpret_cast<char*>(startbyte),sizeof(size_t),len,fid);
        fwrite(reinterpret_cast<char*>(bytenum),sizeof(size_t),len,fid);
        fclose(fid);
    }
};
ostream& operator <<(ostream& os,BlockDictionary& dic)
{
    os << " total " << dic.len << " terms " << endl;
    for(int i=0; i<dic.len; ++i)
    {
        os << " termid = " << dic.termid[i];
        os << " docfq = " << dic.docfq[i];
        os << " startbyte = " << dic.startbyte[i];
        os << " bytenum = " << dic.bytenum[i];
        os << endl;
    }
    return os;
}
#endif
